package cn.usts.edu.lesson03;

/**
 * 龟兔赛跑多线程来实现
 * 乌龟和兔子分别在不同的线程,同时开始
 * */

public class TortoiseRabbitRace implements Runnable{
    String winner;

    @Override
    public void run() {
        for (int i = 1; i < 101; i++) {
            boolean flag = gameIsOver(i);
            System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");

            // 兔子会偷懒,兔子偷懒100毫秒
            if (Thread.currentThread().getName().equals("兔子")){
                try {
                    Thread.sleep(100);//偷懒0.1秒
                    i+=30;// 兔子跑的快
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            if (flag){
                break;
            }
        }
    }

    // 判断比赛是否结束
    public boolean gameIsOver(int steps){
        if (winner!=null){   // 没有获胜者---->gameIsOver=ture;
            return true;
        }else if(steps>=100) {
             // 有人到达终点
                winner = Thread.currentThread().getName();
                System.out.println("winner is ----->"+winner);
                return true;
            }
        return false;
    }


    public static void main(String[] args) {
        TortoiseRabbitRace race = new TortoiseRabbitRace();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}
